package com.example.mvplibrary.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

import com.example.mvplibrary.model.BaseModel;
import com.example.mvplibrary.presenter.BasePresenter;
import com.example.mvplibrary.view.BaseView;

public abstract class BaseLazyFragment<V extends BaseView, M extends BaseModel, P extends BasePresenter<V, M>>
        extends BaseFragment {

    private boolean isFirst = false; //第一次
    private boolean isUserVisible = false; //不可见
    private boolean isLoading = false; //未加载过数据
    public P mPresenter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if (view != null) {
            isFirst = true;
        }
        LazyLoad();
        return view;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            isUserVisible = true;
        } else {
            isVisibleToUser = false;
        }
        LazyLoad();

    }

    private void LazyLoad() {
        if (isFirst && isUserVisible && isLoading) {
            mPresenter = createFragmentLayout();
            if (mPresenter != null) {
                mPresenter.bindView((V) this);
            }
            loadData();
            isLoading = false;

        }


    }

    protected abstract P createFragmentLayout();


    protected abstract void loadData();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.destroyView();
            mPresenter = null;
        }

        isFirst = false;
        isUserVisible = false;
        isLoading = false;
    }
}
